package com.dbpms.controller;

import com.dbpms.pojo.StudentInfo;
import com.dbpms.pojo.User;
import com.dbpms.service.IUserService;
import com.dbpms.until.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class UserController {

    @Autowired
    private IUserService iUserService;

    /**
     * 用户登录
     * @param account
     * @param password
     * @param remember
     * @param req
     * @param resp
     * @param model
     * @return
     */
    @PostMapping("/login")
    public String login(String account, String password, String remember, HttpServletRequest req, HttpServletResponse resp, Model model){

        System.out.println(account);
        System.out.println(password);
        User user = iUserService.login(account,password);
        System.out.println(user);

        if (user != null){


            Cookie re_cookie = new Cookie("remember_cookie","true");
            Cookie account_cookie = new Cookie("account_cookie",user.getUserAccount());
            Cookie pwd_cookie = new Cookie("pwd_cookie",user.getUserPwd());
            if ("true".equals(remember)){
                // 记住密码
                System.out.println("记住密码");

                // 设置cookie保存的时间
                re_cookie.setMaxAge(480*60*60);
                account_cookie.setMaxAge(480*60*60);
                pwd_cookie.setMaxAge(480*60*60);
            }
            else {
                // 取消记住密码
                System.out.println("取消记住密码");

                re_cookie.setMaxAge(0);
                account_cookie.setMaxAge(0);
                pwd_cookie.setMaxAge(0);
            }
            re_cookie.setPath("/");
            account_cookie.setPath("/");
            pwd_cookie.setPath("/");

            resp.addCookie(re_cookie);
            resp.addCookie(account_cookie);
            resp.addCookie(pwd_cookie);

            req.getSession().setAttribute(Constants.USER_SESSION,user);
            System.out.println("sessionID："+req.getSession().getId());

            return "redirect:/notice/listInfo?power="+user.getUserPower();

        }
        System.out.println("=====================");
        model.addAttribute(Constants.MESSAGE,"用户名或者密码不正确");
        model.addAttribute("alert_","danger");
        return "forward:/login.jsp";
    }

    /**
     * 注册功能 转 登录页面
     * @param message
     * @param alert_
     * @param model
     * @return
     */
    @GetMapping("/toLogin")
    public String toLogin(@RequestParam(name = "message",required = false)String message,
                          @RequestParam(name = "alert_",required = false)String alert_,
                          Model model){
        System.out.println("mesa: "+message);
        System.out.println("alert_: "+alert_);

        model.addAttribute("alert_",alert_);
        model.addAttribute(Constants.MESSAGE,message);

        return "forward:/login.jsp";
    }

    /**
     * 注册
     * @param number
     * @param account
     * @param password
     * @param model
     * @return
     */
    @PostMapping("/register")
    public String register(String number, String account, String password,  Model model){

        StudentInfo info = iUserService.ifExitUser(number);
        // 学号存在，就新建用户
        if (info != null){
            int pd = iUserService.addRegisterUser(info.getStudentId(),info.getStudentName(),account,password);
//            int pd = 1;
            if (pd == 1){
                model.addAttribute(Constants.MESSAGE,"注册成功，请重新登录!");
                model.addAttribute("alert_","success");
                return "redirect:/toLogin";
            }else if(pd == -1){
                model.addAttribute(Constants.MESSAGE,"注册失败! 账号已存在！");
            }
            else{
                model.addAttribute(Constants.MESSAGE,"注册失败! 该学号已注册");
            }
        }else{
            model.addAttribute(Constants.MESSAGE,"该学号不存在");
        }
        model.addAttribute("alert_","danger");

        return "forward:/register.jsp";
    }


    /**
     * 前往修改密码页面
     * @return
     */
    @GetMapping("/toUpdatePwd")
    public String toUpdatePwd() {
        return "user/updatePwdUserInfo";
    }
    /**
     * 执行 - 修改密码
     * @param oldPwd ：旧密码
     * @param newPwd ：新密码
     * @return
     */
    @PostMapping("/updatePwd")
    public String updatePwd(String oldPwd,String newPwd,HttpServletRequest req) {

        HttpSession session = req.getSession();
        User user = (User) session.getAttribute(Constants.USER_SESSION);

        int pd = iUserService.updatePwd(oldPwd,newPwd,user.getUserId());
        if (pd>0){
            session.setAttribute("message","修改成功，请重新登录");
            session.setAttribute("alert_","success");
            return "forward:/login.jsp";
        }else if (pd == -1){
            session.setAttribute("message","旧密码错误！");
            return "user/updatePwdUserInfo";
        }else{
            // if (pd == -2)
            session.setAttribute("message","修改密码失败");
            return "user/updatePwdUserInfo";
        }
    }

    /**
     * 退出系统
     * @param req
     * @return
     */
    @GetMapping("/exit")
    public String exit(HttpServletRequest req) {

        HttpSession session = req.getSession(false); // 获取当前会话的session，如果没有则返回null
        if (session != null) {
            session.invalidate(); // 使当前会话无效
        }
        return "forward:/login.jsp";
    }
}
